package org.softmed.rest.generation.uri;

import java.util.List;

import org.softmed.reflection.utils.ReflectionUtil;
import org.softmed.rest.config.Application;
import org.softmed.rest.config.Module;
import org.softmed.rest.generation.scafold.AppConfig;
import org.softmed.rest.generation.scafold.ModConfig;

public class ClassURIBuilder {

	ReflectionUtil reflectUtil = new ReflectionUtil();

	// public void buildAppClasssURIs(App app, Application application) {
	// List<Module> mods = application.getModules();
	// for (Module module : mods) {
	// buildModuleClassURIs(app,);
	// }
	// }

	public void buildModuleClassURIs(AppConfig app, ModConfig mod, Application application,
			Module module) {
		// List<Mod> mods = app.getModules();
		// for (Mod mod : mods) {

		String appURI = application.getRelativeUri();
		if (appURI == null)
			appURI = "";

		String modURI = module.getRelativeUri();
		if (modURI == null)
			modURI = "";

		String completeAppURI = "/" + appURI + "/" + modURI;
		completeAppURI = completeAppURI.replace("//", "/");

		List<Class> classes = mod.getClasses();

		for (Class type : classes) {
			String baseURI = getDefaultRelativeURI(app, type);
			String finalURI = "/" + baseURI;
			finalURI = finalURI.replace("//", "/");
			if (!finalURI.startsWith("/"))
				finalURI = '/' + finalURI;
			app.getUriBuilder().getClassRelativeURIs().put(type.getCanonicalName(), finalURI);
			app.getUriBuilder().getClassAppURIs().put(type.getCanonicalName(), completeAppURI);
		}

		// }

	}

	protected String getDefaultRelativeURI(AppConfig app, Class type) {
		String alias = app.getGenerationConfig().getAlias(type);
		if (alias != null) {
			return alias;
		} else {
			String sname = type.getSimpleName();
			String uri = reflectUtil.getHifenizedName(sname);
			// set to plural
			uri += "s";
			return uri;
		}
	}

}
